import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:rabbit_mobile/i18n/strings.g.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:rabbit_mobile/provide/riverpod_notifier.dart';
import 'package:rabbit_mobile/provide/riverpod_provider.dart';
import 'package:rabbit_mobile/service/home.api.dart';

class Register extends ConsumerStatefulWidget {
  const Register({super.key});

  @override
  _Register createState() => _Register();
}

class _Register extends ConsumerState<Register> {
  /// 輸入框控制器
  late TextEditingController? _textEditingController;

  /// 焦點控制器
  late FocusNode? _focusNode;

  /// 監聽是否有值
  bool isValueNumber = false;

  /// 是否同意條款
  bool isAgree = false;

  @override
  void initState() {
    super.initState();
    _textEditingController = TextEditingController();
    _focusNode = FocusNode();
    _textEditingController!.addListener(() {
      setState(() {
        isValueNumber = _textEditingController!.text.isNotEmpty;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _textEditingController!.dispose();
    _focusNode!.dispose();
  }

  /// 點擊注冊事件處理函數
  void _handleClickRegister() async {
    if (_textEditingController!.text.isEmpty) {
      EasyLoading.showError('手機號不能爲空');
      return;
    }
    RegExp numberRegExp = RegExp(r'^[1][3-9]\d{9}$');
    bool isMatchNumber = numberRegExp.hasMatch(_textEditingController!.text);
    if (!isMatchNumber) {
      EasyLoading.showError("格式錯誤, 請重試...");
      return;
    }
    if (!isAgree) {
      EasyLoading.showError("請同意條款合約");
      return;
    }
    final state = await RegisterPhoneNumberApi.phoneNumberRegisterFetch(_textEditingController!.text);
    if (state.valid) {
      EasyLoading.showError('手機號已注冊');
    }else {
      Beamer.of(context).beamToNamed('/SMSVerificationCode/${_textEditingController!.text}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF00CEA8),
        title: const Text(
          "用戶注冊",
          style: TextStyle(
            fontSize: 14,
            color: Color.fromARGB(255, 255, 255, 255),
          ),
        ),
        leading: IconButton(
          onPressed: () {
            Beamer.of(context).beamBack();
          },
          icon: Image.asset('assets/fanhui_light.png'),
        ),
      ),
      body: GestureDetector(
        onTap: () {
          _focusNode!.unfocus();
        },
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.only(top: 48, bottom: 48),
                alignment: Alignment.center,
                child: const Text(
                  "請輸入手機號",
                  style: TextStyle(fontSize: 16, color: Colors.black),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  height: 48,
                  decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: Colors.grey.shade300))),
                  child: Row(
                    children: [
                      const Padding(
                        padding: EdgeInsets.only(right: 12),
                        child: Text(
                          "手機號",
                          style: TextStyle(fontSize: 14, color: Colors.black),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextField(
                          focusNode: _focusNode,
                          controller: _textEditingController,
                          decoration: const InputDecoration(
                              hintText: "請輸入手機號碼",
                              border: InputBorder.none,
                              hintStyle: TextStyle(fontSize: 12, color: Colors.grey)),
                          cursorColor: const Color(0xFF00CEA8),
                          style: const TextStyle(fontSize: 12, color: Colors.black),
                          keyboardType: TextInputType.number,
                        ),
                      ),
                      isValueNumber
                          ? GestureDetector(
                              onTap: () {
                                _textEditingController!.clear();
                              },
                              child: const Padding(
                                padding: EdgeInsets.only(left: 12),
                                child: Icon(
                                  Icons.close,
                                  size: 18,
                                  color: Colors.grey,
                                ),
                              ),
                            )
                          : Container(),
                    ],
                  ),
                ),
              ),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.only(left: 10, right: 10, top: 48),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          isAgree = !isAgree;
                        });
                      },
                      child: Container(
                        width: 35,
                        height: 35,
                        padding: const EdgeInsets.only(right: 20),
                        child: isAgree
                            ? Image.asset(
                                'assets/isAgree_on.png',
                                fit: BoxFit.contain,
                              )
                            : Image.asset('assets/isAgree.png', fit: BoxFit.contain),
                      ),
                    ),
                    SizedBox(
                      width: 240,
                      child: Text.rich(
                        t.ternms.text(
                          privacyTerms: TextSpan(
                            text: t.privacyTerms,
                            style: const TextStyle(fontSize: 12, color: Color(0xFF00CEA8)),
                          ),
                          serviceTerms: TextSpan(
                            text: t.serviceTerms,
                            style: const TextStyle(fontSize: 12, color: Color(0xFF00CEA8)),
                          ),
                        ),
                        style: const TextStyle(fontSize: 12, color: Colors.grey),
                        maxLines: 3,
                      ),
                    )
                  ],
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: TextButton(
                  style: ButtonStyle(
                    overlayColor: WidgetStateProperty.all(Colors.transparent), // 移除水波纹效果
                  ),
                  onPressed: _handleClickRegister,
                  child: Container(
                    alignment: Alignment.center,
                    width: double.infinity,
                    height: 50,
                    decoration: const BoxDecoration(
                        color: Color(0xFF00CEA8), borderRadius: BorderRadius.all(Radius.circular(10))),
                    child: const Text(
                      "下一步",
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 12),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    "需要幫助",
                    style: TextStyle(fontSize: 12, color: Color(0xFF00CEA8)),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
